package com.zirenx.sys.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Inject;
import com.zirenx.sys.model.SysRoleMenu;
import com.zirenx.sys.model.SysUserRole;
import com.zirenx.utils.tree.BuildTree;
import com.zirenx.utils.StringUtils;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.zirenx.sys.model.SysMenu;
import com.zirenx.utils.tree.Tree;

public class SysMenuService {

	private SysMenu dao = new SysMenu().dao();

	@Inject
	SysRoleMenuService sysRoleMenuService;

	public List<SysMenu> list() {
		return dao.findAll();
	}
	
	/**
	 * 分页查询
	 * @param pageNumber
	 * @param pageSize
	 * @param kv
	 * @return
	 */
	public Page<SysMenu> paginate(int pageNumber,int pageSize,Kv kv) {
		StringBuffer sb = new StringBuffer("select * from "+dao.getTableName()+" t where 1=1 ");
		
		SqlPara sqlPara = new SqlPara();
		String name = kv.getStr("name");
		if(!StringUtils.isEmpty(name)) {
			sb.append(" and t.name = ?");
			sqlPara.addPara(name);
		}
		String parentId = kv.getStr("parentId");
		if(!StringUtils.isEmpty(parentId)) {
			sb.append(" and t.parent_id = ?");
			sqlPara.addPara(parentId);
		}else {
			sb.append(" and t.parent_id = 0");
		}
		
		sqlPara.setSql(sb.toString());
		
		return dao.paginate(pageNumber, pageSize, sqlPara);
	}

	/**
	 * 根据用户id,获取用户下所有角色菜单
	 * @param userId
	 * @return
	 */
	public List<SysMenu> getMenusByUserId(Long userId) {
		SysUserRole sysUserRole = new SysUserRole();
		SysRoleMenu sysRoleMenu = new SysRoleMenu();

		String sql = "SELECT DISTINCT c.* FROM "+sysUserRole.getTableName()+" a " +
				"INNER JOIN "+sysRoleMenu.getTableName()+" b on b.role_id = a.role_id " +
				"INNER JOIN "+dao.getTableName()+" c on c.id = b.menu_id " +
				"where a.user_id = ? and c.parent_id = ? ORDER BY c.order_num ";

		List<SysMenu> list = dao.find(sql,userId,0);
		for (SysMenu sysMenu : list) {
			sysMenu.setItems(dao.find(sql,userId,sysMenu.getId()));
		}
		return list;
	}

	public List<SysMenu> getMenus() {
		List<SysMenu> list = dao.find("select * from "+dao.getTableName()+" t where parent_id=0");
		for (SysMenu sysMenu : list) {
			sysMenu.setItems(dao.find("select * from "+dao.getTableName()+" t where parent_id=?",sysMenu.getId()));
		}
		return list;
	}

	public List<SysMenu> getList() {
		List<SysMenu> list = dao.find("select * from "+dao.getTableName()+" t ");
		return list;
	}

	public Tree<SysMenu> getTree() {
		List<Tree<SysMenu>> trees = new ArrayList<Tree<SysMenu>>();
		List<SysMenu> list = getList();
		for (SysMenu sysMenu : list){
			Tree<SysMenu> tree = new Tree<SysMenu>();
			tree.setId(sysMenu.getId().toString());
			tree.setParentId(sysMenu.getParentId().toString());
			tree.setText(sysMenu.getName());
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		Tree<SysMenu> t = BuildTree.build(trees);
		return t;
	}

	public Tree<SysMenu> getTree(String roleId) {
		// 根据roleId查询权限
		List<SysMenu> menus = getList();
		List<Long> menuIds = sysRoleMenuService.getListMenuIdByRoleId(roleId);
		List<Long> temp = menuIds;
		for (SysMenu menu : menus) {
			if (temp.contains(menu.getParentId())) {
				menuIds.remove(menu.getParentId());
			}
		}
		List<Tree<SysMenu>> trees = new ArrayList<Tree<SysMenu>>();
		List<SysMenu> SysMenus = getList();
		for (SysMenu sysSysMenu : SysMenus) {
			Tree<SysMenu> tree = new Tree<SysMenu>();
			tree.setId(sysSysMenu.getId().toString());
			tree.setParentId(sysSysMenu.getParentId().toString());
			tree.setText(sysSysMenu.getName());
			Map<String, Object> state = new HashMap<>(16);
			Long menuId = sysSysMenu.getId();
			if (menuIds.contains(menuId)) {
				state.put("selected", true);
			} else {
				state.put("selected", false);
			}
			tree.setState(state);
			trees.add(tree);
		}
		// 默认顶级菜单为０，根据数据库实际情况调整
		Tree<SysMenu> t = BuildTree.build(trees);
		return t;
	}
	
	public SysMenu findById(String id) {
		return dao.findById(id);
	}

	public List<SysMenu> findByParentId(String id){
		if(StringUtils.isEmpty(id)){
			return new ArrayList<>();
		}
		return dao.find("select * from "+dao.getTableName()+" t where parent_id=?",id);
	}

	void getChildren(SysMenu sysMenu,List<SysMenu> children){
		children.add(sysMenu);

		List<SysMenu> parents = findByParentId(sysMenu.getId().toString());

		for (SysMenu menu : parents){
			findByParentId(menu.getId().toString());
			getChildren(menu,children);
		}
	}

	public void delete(String id) {
		SysMenu sysMenu = findById(id);

		List<SysMenu> children = new ArrayList<>();
		//递归所有子级
		getChildren(sysMenu,children);

		for (SysMenu menu : children){
			menu.delete();	//删除
		}
	}
	
}
